--less spaghetti plox

Chooser = States:Register("chooser", Class:Create())

local t;

local chooser_ped;

local curr_team = 1;

function Chooser:Start()
	t = teams
	
	chooser_ped = createPed(t[1][5], -2700.57129, 1595.03223, 225.75781, 90)
	setPedAnimation(chooser_ped, "DANCING", "dance_loop")
	
	fadeCamera(true, 0)
	showPlayerHudComponent("all", false)
	onClientRender:Handle(game_onRender)
	onClientClick:Handle(onClick)
	
	showCursor(true)

	setCameraMatrix(-2706, 1593.5, 226, -2700, 1593.5, 226)
end

function Chooser:Stop()
	
end


function game_onRender()
	Screen:Image(0, 0, sx, sy, "resources/img/team_choose.png")
	dxDrawImageSection(sx / 2 - 256 + sx / 5, 0, 512, 200, 0, 0, 512, 200, "resources/img/logo.png")
	
	-- TEXT
	
	-- Between LEFT and RIGHT buttons - 150,836-541,874
	dxDrawText(t[curr_team][1], sx * 150 / 1280, sy * 836 / 960, sx * 541 / 1280, sy * 874 / 960, tocolor(t[curr_team][2], t[curr_team][3], t[curr_team][4], 255), 1.5, "bankgothic", "center", "center")
	
	-- Header of the players list - 674,228-1194,301
	dxDrawText(lang.players, sx * 674 / 1280, sy * 228 / 960, sx * 1194 / 1280, sy * 301 / 960, tocolor(255, 255, 255, 255), 1.5, "bankgothic", "center", "center")
	
	players = {}
	
	-- Players in the team - 674,312-1194,750	
	for k,v in ipairs(getPlayersInTeam(getTeamFromName(t[curr_team][1]))) do
		table.insert(players, getPlayerName(v))
	end

	tplayers = table.concat(players, "\n")
	dxDrawText(tplayers, sx * 674 / 1280, sy * 312 / 960, sx * 1194 / 1280, sy * 750 / 960, tocolor(255, 255, 255, 255), 0.8, "bankgothic", "center", "top")
	-- Join button - 674,827-1194,883
	dxDrawText(lang.join, sx * 674 / 1280, sy * 827 / 960, sx * 1194 / 1280, sy * 883 / 960, tocolor(255, 255, 255, 255), 1.5, "bankgothic", "center", "center")
end

function onClick(_, button, state, x, y)
	if button == "left" and state == "down" then
		-- LEFT button - 101,836-140,874		
		if x > sx * 101 / 1280 and x < sx * 140 / 1280 and
		   y > sy * 836 / 960 and y < sy * 874 / 960 then
		   
			curr_team = curr_team - 1
		   
			if curr_team == 0 then
				curr_team = 3
			end
			
			setElementModel(chooser_ped, t[curr_team][5])
		end
		
		-- RIGHT button - 551,836-590,874
		if x >= sx * 551 / 1280 and x <= sx * 590 / 1280 and
		   y >= sy * 836 / 960 and y <= sy * 874 / 960 then
		   
			curr_team = curr_team + 1
		   
			if curr_team == 4 then
				curr_team = 1
			end
			setElementModel(chooser_ped, t[curr_team][5])
		end
		
		-- JOIN button - 674,827-1194,883
		if x >= sx * 674 / 1280 and x <= sx * 1194 / 1280 and
		   y >= sy * 827 / 960 and y <= sy * 883 / 960 then
		   
			onClientChooseTeam:ServerTrigger(getLocalPlayer(), curr_team)
			
			destroyElement(chooser_ped)
		   
			onClientClick:Remove(onClick)
			onClientRender:Remove(game_onRender)
			showPlayerHudComponent("all", true)
		   
			States:Change("lobby")
		end
	end
end